import { useRouter } from "vue-router";
import type { Container, Pod } from "../k8s";

type PodOptionReq = {
  cluster: string;
  namespace: string;
  name?: string;
  containerName?: string;
  pod?: Pod;
  container?: Container;
};

export const usePodOperation = () => {
  const router = useRouter();

  const openTerminal = (req: PodOptionReq) => {
    const routeUrl = router.resolve({
      path: "/terminal",
      query: {
        cluster: req.cluster,
        namespace: req.namespace,
        pod: req.name ?? req.pod?.metadata.name,
        container:
          req.containerName ??
          req.container?.name ??
          (req.pod?.spec?.containers && req.pod?.spec?.containers.length > 0
            ? req.pod?.spec?.containers[0].name
            : ""),
        type: "terminal"
      }
    });

    window.open(routeUrl.href, "_blank");
  };

  const openTerminalLogs = (req: PodOptionReq) => {
    const routeUrl = router.resolve({
      path: "/terminal",
      query: {
        cluster: req.cluster,
        namespace: req.namespace,
        pod: req.name ?? req.pod?.metadata.name,
        container:
          req.containerName ??
          req.container?.name ??
          (req.pod?.spec?.containers && req.pod?.spec?.containers.length > 0
            ? req.pod?.spec?.containers[0].name
            : ""),
        type: "log"
      }
    });

    window.open(routeUrl.href, "_blank");
  };

  return {
    router,
    openTerminal,
    openTerminalLogs
  };
};
